package top.laoshuzi.server.common.utils

import org.springframework.beans.BeanUtils
import org.springframework.beans.FatalBeanException

import java.beans.PropertyDescriptor
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.ArrayList
import java.util.Collections

object BeanPropertyUtils {

    fun findNullProperties(source: Any): Array<String> {
        val actualEditable = source.javaClass
        val targetPds = BeanUtils.getPropertyDescriptors(actualEditable)
        val ignoreList = emptyList<String>()
        val nullProperties = ArrayList<String>()
        for (targetPd in targetPds) {
            val readMethod = targetPd.readMethod
            if (readMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.name))) {
                try {
                    if (!Modifier.isPublic(readMethod.declaringClass.modifiers)) {
                        readMethod.isAccessible = true
                    }
                    val `object` = readMethod.invoke(source)
                    if (`object` == null) {
                        nullProperties.add(targetPd.name)
                    }
                } catch (ex: Throwable) {
                    throw FatalBeanException(
                            "Could not copy property '" + targetPd.name + "' from source to target", ex)
                }
            }
        }

        val properties =
                if (nullProperties.isEmpty())
                    arrayOf<String>()
                else
                    arrayOfNulls<String>(nullProperties.size)

        return nullProperties.toTypedArray()
    }

}
